package com.jch.ft.codec;

import com.jch.ft.util.SerializationUtil;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToByteEncoder;

public class ObjectEncoder extends MessageToByteEncoder {

    private Class<?> genericClass;

    public ObjectEncoder(Class<?> genericClass) {
        this.genericClass = genericClass;
    }

    @Override
    protected void encode(ChannelHandlerContext ctx, Object msg, ByteBuf out) throws Exception {
        if (genericClass.isInstance(msg)) { // 检查对象类型
            byte[] dataBytes = SerializationUtil.serialize(msg);
            out.writeInt(dataBytes.length);
            out.writeBytes(dataBytes);
        }
    }
}
